﻿//渲染表格数据
layui.use(['table', 'laypage', 'layer', 'form'], function () {
    var table = layui.table;
    var laypage = layui.laypage;
    var layer = layui.layer;
    var form = layui.form;
    var $ = layui.$;

    //绑定戴标原因的枚举
    $(document).ready(function () {
        $.ajax({
            url: 'http://10.31.60.18:8000/EarTagGetRout/api/EarTagRead/zhuanMark', // 后端枚举数据接口地址
            type: 'get',
            dataType: 'json',
            success: function (res) {
                var enumData = res; // 直接使用返回的数据
                var select = $('#reason');
                $.each(enumData, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.value).text(item.txt);
                    select.append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });

    //绑定耳号
    $(document).ready(function () {
        $.ajax({
            url: 'http://10.31.60.18:8000/EarTagGetRout/api/EarTagRead/BindNumber',
            type: 'get',
            dataType: 'json',
            success: function (res) {
                var enumData = res.data; // 直接使用返回的数据
                var select = $('#ear');
                $.each(enumData, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.earNumber).text(item.earNumber);
                    select.append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });

    //绑定戴标原因的枚举添加用
    $(document).ready(function () {
        $.ajax({
            url: 'http://10.31.60.18:8000/EarTagGetRout/api/EarTagRead/zhuanMark', // 后端枚举数据接口地址
            type: 'get',
            dataType: 'json',
            success: function (res) {
                var enumData = res; // 直接使用返回的数据
                var select = $('#reasonsAdd');
                $.each(enumData, function (index, item) {
                    // 使用正确的字段添加选项到下拉框中
                    var option = $('<option>').val(item.value).text(item.txt);
                    select.append(option);
                });
                // 手动触发 layui 组件的渲染
                layui.form.render('select');
            },
            error: function () {
                // 处理 AJAX 请求失败的情况
                console.error('Failed to fetch data for dropdown.');
            }
        });
    });

    var pageSize = 15; // 每页显示条数
    //获取列表
    function getListData(pageIndex) {
        //获取查询条件
        var earNumber = $('#earNumber').val();
        var oldEarTag = $("#oldEarTag").val();
        var newEarTag = $("#newEarTag").val();
        var reason = $("#reason").val();
        //ajax后台交互
        $.ajax({
            url: 'http://10.31.60.18:8000/EarTagGetRout/api/EarTagRead/MarkShow',
            type: 'get',
            dataType: 'json',
            //参数
            data: {
                pageIndex: pageIndex,
                pageSize: pageSize,
                earNumber: earNumber,
                oldEarTag: oldEarTag,
                newEarTag: newEarTag,
                reason: reason,
            },
            success: function (res) {
                table.render({
                    //挂载的表格id
                    elem: '#ID-table-demo-setRowChecked',
                    cols: [
                        [
                            { type: 'checkbox' },

                            { field: 'earNumber', title: '耳号' },
                            { field: 'oldEarTag', title: '当前电子耳号' },
                            { field: 'newEarTag', title: '新电子耳号' },
                            {
                                field: 'reason', title: '戴标原因', align: 'center',
                                templet: function (data) {
                                    if (data.reason == 1) return '新戴';
                                    if (data.reason == 2) return '脱落补戴';
                                    if (data.reason == 3) return '不读补戴';
                                    if (data.reason == 4) return '不符补戴';
                                    if (data.reason == 5) return '解绑';
                                }
                            },
                            { field: 'createBy', title: '创建人' },
                            {
                                field: 'createDate', title: '创建时间',
                                templet: function (data) {
                                    if (data.createDate != null) {
                                        return data.createDate.substring(0, 10)
                                    }
                                },
                            },
                            { title: '操作', toolbar: '#barDemo' }
                        ]
                    ],
                    data: res.datas
                });

                //分页
                laypage.render({
                    //挂载的分页id
                    elem: 'pagesbox',
                    count: res.totalCount,
                    limit: pageSize,
                    curr: pageIndex,
                    layout: ['count', 'prev', 'page', 'next', 'skip'],
                    jump: function (obj, first) {
                        if (!first) {
                            getListData(obj.curr);
                        }
                    }
                });
            }
        });
    }

    $('#searchBtn').on('click', function () {
        getListData(1);
    });

    // 单删除
    function deleteData(markId) {
        $.ajax({
            url: `http://10.31.60.18:8000/EarTagSetRout/api/EarTag/MarkDelete?MarkId=${markId}`,
            type: 'delete',
            success: function (res) {
                if (res.code == 200) {
                    layer.msg('删除成功');
                    getListData(1);
                } else {
                    layer.msg('删除失败');
                }
            },
            error: function () {
                layer.msg('删除请求失败');
            }
        });
    }
    //反填
    function editData(markId) {
        $.ajax({
            url: 'http://10.31.60.18:8000/EarTagGetRout/api/EarTagRead/MarkBackfill?markId=' + markId,
            type: 'get',
            contentType: 'application/json',
            success: function (res) {
                if (res.code == 200) {
                    // 填充编辑数据
                    $("[name='markId']").val(res.data.markId);
                    $("#ear").val(res.data.earNumber);
                    $("#oldEarTags").val(res.data.oldEarTag);
                    $("#newEarTags").val(res.data.newEarTag);
                    $("#reasonsAdd").val(res.data.reason);

                    // 反填下拉框的值
                    $("#breed").next().find("input").val(res.data.reason);
                    console.log(res.data.markId)
                    console.log(res.data.earNumber)
                    layer.open({
                        type: 1,
                        title: "修改新记录",
                        shift: 2,
                        area: ['600px', '500px'],
                        shade: 0,
                        shadeClose: false,
                        content: $("#add-main"),
                        success: function (layero, index) {
                            layui.form.render(); // 重新渲染表单
                        }
                    });
                } else {
                    layer.msg(res.msg, { icon: 5 });
                }
            },
            error: function (err) {
                // 处理请求错误
            }
        });
    }

    // 监听工具条，实现删除功能
    table.on('tool(ID-table-demo-setRowChecked)', function (obj) {
        var data = obj.data;
        if (obj.event == 'edit') {
            editData(data.markId);
        }
        if (obj.event == 'delete') {
            layer.confirm('确定删除吗？', function (index) {
                deleteData(data.markId); // 传递正确的数据项ID
                layer.close(index);
            });
        }
    });

    // 批量删除
    $(".delAll_btn").click(function () {
        var checkStatus = table.checkStatus('ID-table-demo-setRowChecked'),
            data = checkStatus.data,
            markId = "";
        if (data.length > 0) {
            for (var i in data) {
                markId += data[i].markId + ",";
            }
            markId = markId.substring(0, markId.length - 1);
            console.log(markId);
            layer.confirm('确定删除选中的记录？', { icon: 3, title: '提示信息' }, function (index) {
                $.ajax({
                    url: `http://10.31.60.18:8000/EarTagSetRout/api/EarTag/MarkBatchDelete?markId=${markId}`,

                    type: 'delete',
                    success: function (res) {
                        if (res.code == 200) {
                            layer.msg("批量删除成功");
                            getListData(1);
                        } else {
                            layer.msg("批量删除失败");
                        }
                    },
                    error: function () {
                        layer.msg('批量删除请求失败');
                    }
                });
                layer.close(index);
            });
        } else {
            layer.msg("请选择需要删除的记录");
        }
        console.log(checkStatus);
    });

    // 监听表单提交及修改
    form.on('submit(save)', function (data) {
        if ($("[name='markId']").val() == "") {
            var formData = {
                EarNumber: $("[name='earNumber']").val(),
                OldEarTag: $("input[name='oldEarTag']").val(),
                NewEarTag: $("input[name='newEarTag']").val(),
                Reason: $("#reasonsAdd").val(),
                CreateBy: "张三",
                CreateDate: new Date()
            };
            $.ajax({
                url: 'http://10.31.60.18:8000/EarTagSetRout/api/EarTag/MarkCreate', // 替换为您的后端API接口地址
                type: 'post',
                data: JSON.stringify(formData),
                contentType: 'application/json',
                success: function (res) {
                    if (res.code == 200) {
                        layer.msg(res.msg, { icon: 1 });
                        setTimeout(function () {
                            location.href = '/EarTag/ShowBeginning'
                        }, 1000)
                    } else {
                        layer.msg(res.msg, { icon: 2 });
                    }
                },
                error: function () {
                    // 获取单个字段的输入框元素
                    const ear = document.getElementById('ear');

                    if (ear.value.trim() === '') {
                        layer.msg('耳号不能为空！');
                        return;
                    }
                    // 获取单个字段的输入框元素
                    const oldEarTags = document.getElementById('oldEarTags');

                    if (oldEarTags.value.trim() === '') {
                        layer.msg('当前电子耳号不能为空！');
                        return;
                    }
                    // 获取单个字段的输入框元素
                    const newEarTags = document.getElementById('newEarTags');

                    if (newEarTags.value.trim() === '') {
                        layer.msg('新电子耳号不能为空！');
                        return;
                    }
                    // 获取单个字段的输入框元素
                    const reasonsAdd = document.getElementById('reasonsAdd');

                    if (reasonsAdd.value.trim() === '') {
                        layer.msg('戴表原因不能为空！');
                        return;
                    }
                }
            });
            return false; // 阻止表单跳转
        }
        else {
            var formData = {
                markId: $("[name='markId']").val(), // 获取主键id
                EarNumber: $("[name='earNumber']").val(),
                OldEarTag: $("input[name='oldEarTag']").val(),
                NewEarTag: $("input[name='newEarTag']").val(),
                Reason: parseInt($("#reasonsAdd").val()),
                CreateBy: "张三",
                CreateDate: new Date(),
                UpdateBy: "李四",
                UpdateDate: new Date()
            };
            $.ajax({
                url: 'http://10.31.60.18:8000/EarTagSetRout/api/EarTag/MarkUpdate', // 替换为您的后端API接口地址
                type: 'put',
                data: JSON.stringify(formData),
                contentType: 'application/json',
                success: function (res) {
                    if (res.code == 200) {
                        layer.msg(res.msg, { icon: 1 });
                        setTimeout(function () {
                            location.href = '/EarTag/ShowBeginning'
                        }, 1000)
                    } else {
                        layer.msg(res.msg, { icon: 2 });
                    }
                },
                error: function () {
                    // 获取单个字段的输入框元素
                    const ear = document.getElementById('ear');

                    if (ear.value.trim() === '') {
                        layer.msg('耳号不能为空！');
                        return;
                    }
                    // 获取单个字段的输入框元素
                    const oldEarTags = document.getElementById('oldEarTags');

                    if (oldEarTags.value.trim() === '') {
                        layer.msg('当前电子耳号不能为空！');
                        return;
                    }
                    // 获取单个字段的输入框元素
                    const newEarTags = document.getElementById('newEarTags');

                    if (newEarTags.value.trim() === '') {
                        layer.msg('新电子耳号不能为空！');
                        return;
                    }
                    // 获取单个字段的输入框元素
                    const reasonsAdd = document.getElementById('reasonsAdd');

                    if (reasonsAdd.value.trim() === '') {
                        layer.msg('戴表原因不能为空！');
                        return;
                    }
                }
            });
            return false; // 阻止表单跳转
        }
    });

    $(function () {
        // 初始化加载数据
        getListData(1);
    })
})

var $ = layui.$;
function onAddBtn() {
    $('#add-form')[0].reset(); // 重置表单
    var laydate = layui.laydate;
    // 渲染
    laydate.render({
        elem: '#storageDate'
    });

    layer.open({
        type: 1,
        title: "添加新记录",

        shift: 2,
        area: ['600px', '500px'],
        shade: 0,
        shadeClose: false,
        content: $("#add-main"),
        success: function (layero, index) {
        }
    });
}